// packageI/newPoster/newPoster.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    keywork: "",
    // 已选类型
    active: 0,
    show: false,
    info: [],
    // 已选标签
    labelSelect: 0,
    poplabel: "",
    // 弹窗列表数组
    popupList: [],
    popupPage: 1,
    popupLast: 1,
    // 海报是否显示
    posterShow: false,
    // 前端生成图片参数
    posterData: {
      poster_data: null,
      background: {}
    },
    // 已生成的图片参数
    defaultImg: "",
    // 选择显示的海报封面索引
    showPosterInd: 0,
    fmPosterShow: false,
    childImgaeBase: "",
    leftImg: "https://mini-app-img-1251768088.cos.ap-guangzhou.myqcloud.com/images%2FposterCenter%2Fleft.png",
    leftImg1: "https://mini-app-img-1251768088.cos.ap-guangzhou.myqcloud.com/images%2FposterCenter%2Fleft2.png",
    rightImg: "https://mini-app-img-1251768088.cos.ap-guangzhou.myqcloud.com/images%2FposterCenter%2Fright.png",
    rightImg1: "https://mini-app-img-1251768088.cos.ap-guangzhou.myqcloud.com/images%2FposterCenter%2Fright2.png",
    is_record: false,

    isLoadMore: true,
    page: 1,
    total_page: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    wx.setNavigationBarTitle({
      title: '海报中心',
    })
    this.getData();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if (this.data.isLoadMore) {
      this.getMoreData();
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  showInIint(key) {
    this.setData({
      show: key,
      popupPage: 1,
      popupLast: 1,
      popupLast: 1,
      popupList: []
    })
  },
  showInMethod() {
    this.showInIint(true);
    this.setData({
      poplabel: this.data.labelSelect
    })
    let urlstr = app.getNetAddresss("plugin.poster-center.frontend.controllers.index.getLabel");
    app._getNetWork({
      url: urlstr,
      data: {
        page: this.data.popupPage
      },
      success: (response) => {
        let res = response.data;
        if (res.result == 1) {
          this.setData({
            popupList: res.data.list.data,
            popupLast: res.data.list.last_page
          })
        }
      },
    });
  },
  popupMore() {
    if (this.data.popupPage >= this.data.popupLast) return;
    this.setData({
      popupPage: this.data.popupPage + 1
    })
    let urlstr = app.getNetAddresss("plugin.poster-center.frontend.controllers.index.getLabel");
    app._getNetWork({
      url: urlstr,
      data: {
        page: this.data.popupPage
      },
      success: (response) => {
        let res = response.data;
        if (res.result == 1) {
          this.setData({
            popupList: this.data.popupList.concat(res.data.list.data),
          })
        }
      },
    });
  },
  cancelTap() {
    this.setData({
      poplabel: this.data.labelSelect
    })
    this.showInIint(false);
  },
  confirmTap() {
    this.setData({
      labelSelect: this.data.poplabel
    })
    this.showInIint(false);
    this.getData();
  },
  chooseTag(e) {
    let item = e.currentTarget.dataset.item;
    if(this.data.poplabel == item.id){
      this.setData({
        poplabel :0
      })
      return
    }
    this.setData({
      poplabel: item.id
    })
  },
  savePoster(img){
    // var times = _this.data.timeend - _this.data.timestart
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success() {
              console.log('授权成功');
            }
          });
        }
      }
    });
    var imgSrc = img;
    wx.downloadFile({
      url: imgSrc,
      success: function (res) {
        console.log(res);
        // 图片保存到本地
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: function (data) {
            wx.showToast({
              title: '保存成功',
              icon: 'none',
              duration: 2000
            });
          },
          fail: function (err) {
            console.log(err);
            if (err.errMsg === 'saveImageToPhotosAlbum:fail auth deny') {
              console.log('当初用户拒绝，再次发起授权');
              wx.openSetting({
                success(settingdata) {
                  if (settingdata.authSetting['scope.writePhotosAlbum']) {
                    wx.showToast({
                      icon: 'none',
                      title: '获取权限成功,再次长按保存图片',
                      duration: 1500
                    });
                  } else {
                    wx.showToast({
                      icon: 'none',
                      title: '获取权限失败,保存图片需要用户授权',
                      duration: 1500
                    });
                  }
                }
              });
            }
          },
          complete(res) {
            console.log(res);
          }
        });
      }
    });
  },
  creatPoster() {
    if(this.data.info.poster_list.data[this.data.showPosterInd].background_poster_url){
      this.savePoster(this.data.info.poster_list.data[this.data.showPosterInd].background_poster_url)
      return
    }
    this.setData({
      posterData: {
        poster_data: null,
        background: {}
      },
    })
    wx.showLoading({
      title: '海报加载中',
    })
    let id = this.data.info.poster_list.data[this.data.showPosterInd].id;
    let urlstr = app.getNetAddresss("plugin.poster-center.frontend.controllers.index.createPoster");
    app._getNetWork({
      url: urlstr,
      data: {
        poster_id: id
      },
      success: (response) => {
        wx.hideLoading()
        let res = response.data;
        if (res.result == 1) {
          this.setData({
            posterShow: true,
            is_record: res.data.is_record,
          })
          if (res.data.is_record) {
            this.data.info.poster_list.data[this.data.showPosterInd].background_poster_url = res.data.url;
            this.setData({
              defaultImg: res.data.url
            })
          } else {
            this.data.posterData.background.type = "background";
            this.data.posterData.background.src = res.data.model && res.data.model.background ? res.data.model.background : "";
            this.data.posterData.poster_data = res.data.model && res.data.model.style_data ? res.data.model.style_data : [];
            console.log(this.data.posterData, 'dddddddd')
            this.setData({
              defaultImg: "",
              posterData: this.data.posterData
            })
          }
          console.log(res)
        }
      },
      fail:(err)=>{
        wx.hideLoading()
      }
    });
  },
  // 海报生成完成后 子组件传递
  finish(e) {
    console.log(e)
    let datainfo = e.detail;
    this.setData({
      childImgaeBase: datainfo,
      ['info.poster_list.data[' + this.data.showPosterInd + '].background_poster_url']: datainfo
    })
    if (!this.data.is_record) {
      this.uoloadPoster();
    }
  },
  // 上传海报
  uoloadPoster() {
    let wx_token = wx.getStorageSync('wx_token');
    let session = wx.getStorageSync('session');
    let urlStr = app.getNetAddresss('plugin.poster-center.frontend.controllers.index.uploadLocal');
    urlStr += '&poster_id=' + this.data.info.poster_list.data[this.data.showPosterInd].id;
    urlStr += '&3rd_session=' + session;
    urlStr += '&ingress=ingress';
    wx.uploadFile({
      url: urlStr,
      filePath: this.data.info.poster_list.data[this.data.showPosterInd].background_poster_url,
      name: 'file',
      formData: {
        // 和服务器约定的token, 一般也可以放在header中
        '_wx_token': wx.getStorageSync('wx_token'),
        'ingress': 0
      },
      header: {
        "Content-Type": "multipart/form-data",
        Cookie: "PHPSESSID=" + wx_token,
      },
      success: (res) => {
        let data = JSON.parse(res.data);
        if (data.result == 1) {
          this.addPosterRecord(data.data.img_url);
        }
      },
      fail: function (e) {
        console.log(e)
      }
    });
  },
  // 上传海报记录
  addPosterRecord(imageurl) {
    let urlstr = app.getNetAddresss("plugin.poster-center.frontend.controllers.index.posterRecord");
    app._postNetWork({
      url: urlstr,
      data: {
        image: imageurl,
        poster_id: this.data.info.poster_list.data[this.data.showPosterInd].id
      },
      success: (response) => {
        let res = response.data;
        if (res.result == 1) {
          console.log(res)
        } else {
          app.tips(res.msg)
        }
      },
    });
  },
  showPoster(e) {
    console.log(e)
    let {
      index
    } = e.currentTarget.dataset;
    this.setData({
      showPosterInd: index,
      fmPosterShow: true
    })
  },
  closeFm() {
    this.setData({
      defaultImg: [],
      fmPosterShow: false
    })
  },
  scrollLeft() {
    if (this.data.showPosterInd == 0) {
      app.tips('已经是第一张')
      return;
    }
    if (this.data.showPosterInd > 0) {
      this.setData({
        showPosterInd: Number(this.data.showPosterInd) - 1
      })
    }
  },
  scrollRight() {
    if (this.data.showPosterInd >= this.data.info.poster_list.data.length - 1) {
      app.tips('已经是最后一张')
      return;
    }
    if (this.data.showPosterInd < this.data.info.poster_list.data.length) {
      this.setData({
        showPosterInd: Number(this.data.showPosterInd) + 1
      })
    }
  },
  searchMethod(e) {
    this.setData({
      keywork: e.detail
    })
    this.getData();
  },
  tapType(e) {
    let {
      id
    } = e.currentTarget.dataset;
    this.setData({
      active: id
    })
    this.getData();
  },
  tapLabel(e) {
    let {
      id
    } = e.currentTarget.dataset;
    this.setData({
      labelSelect: id
    })
    this.getData();
  },
  getData() {
    let json = {
      poster_type: this.data.active ? this.data.active : "",
      title: this.data.keywork ? this.data.keywork : "",
      label_id: this.data.labelSelect ? this.data.labelSelect : ""
    };
    let urlstr = app.getNetAddresss("plugin.poster-center.frontend.controllers.index.index");
    app._getNetWork({
      url: urlstr,
      data: json,
      success: (response) => {
        let res = response.data;
        if (res.result == 1) {
          this.setData({
            info: res.data,
            isLoadMore: true,
            total_page: res.data.poster_list.last_page
          })
        }
      },
    });
  },
  getMoreData() {
    this.data.isLoadMore = false;
    if (this.data.page >= this.data.total_page) {
      return;
    } else {
      this.page = this.page + 1;
      this.setData({
        page: Number(this.data.page) + 1
      })
      let json = {
        page: this.page,
        poster_type: this.data.active ? this.data.active : "",
        title: this.data.keywork,
        label_id: this.data.labelSelect ? this.data.labelSelect : ""
      };
      let urlstr = app.getNetAddresss("plugin.poster-center.frontend.controllers.index.index");
      app._getNetWork({
        url: urlstr,
        data: json,
        success: (response) => {
          let res = response.data;
          console.log(res)
          if (res.result == 1) {
            let myData = res.data.poster_list.data;
            this.data.info.poster_list.data = this.data.info.poster_list.data.concat(myData);
            this.data.isLoadMore = true;
            this.setData({
              info: this.data.info,
              total_page: res.data.poster_list.last_page
            })
          }
        },
      });
    }
  }
})